import { Button, Card, Collapse, Input, InputRef, message, Modal } from 'antd'
import { SearchOutlined, ExclamationCircleOutlined } from '@ant-design/icons'
import UploadPdf from './uploadPdf'
import Bread from '@/component/bread/bread'
import axios from '@/http'
import { useContext, useEffect, useRef, useState } from 'react'
import { TPdf } from '@type'
import './pdf.scss'
import { bound } from '@/util'
import { AppContext } from '@/App'
import { baseUrl } from '@/http'
const { confirm } = Modal

const { Panel } = Collapse

type TResPdf = {
  direction: string
  pdfArr: TPdf[]
}
const Pdf = () => {
  useEffect(() => {
    getPdfList()
  }, [])
  const {
    store: { status, username }
  } = useContext(AppContext)
  const [pdfList, setPdfList] = useState<TResPdf[]>([])
  const [pdfAllList, setPdfAllList] = useState<TPdf[]>([])
  const getPdfList = () => {
    axios.get('/pdf/search').then(res => {
      const result = res.data.data
      setPdfAllList(result)
      setPdfList(transformResult(res.data.data))
    })
  }

  const transformResult = (res: TPdf[]) => {
    const temRes: TResPdf[] = []
    res.forEach(item => {
      const findRes = temRes.find(temItem => temItem.direction === item.direction)
      findRes ? findRes.pdfArr.push(item) : temRes.push({ direction: item.direction, pdfArr: [item] })
    })
    return temRes
  }
  const downloadPdf = (id: number) => {
    axios.get('/util/valid').then(res => {
      if (res.data.data) {
        let aTag: HTMLAnchorElement | null = document.createElement('a')
        aTag.href = baseUrl + '/pdf/download?id=' + id
        aTag.click()
        aTag = null
      }
    })
  }
  const showDeleteConfirm = (id: number) => {
    confirm({
      title: '删除博客?',
      icon: <ExclamationCircleOutlined />,
      content: '你确定要删除该博客？',
      okText: '确定',
      okType: 'danger',
      cancelText: '取消',
      onOk() {
        startDel(id)
      }
    })
  }
  const startDel = (id: number) => {
    axios
      .post('/pdf/del', {
        id
      })
      .then(res => {
        if (res.data.error === -1) {
          message.success('删除成功')
          getPdfList()
        }
      })
  }
  const inputDom = useRef<InputRef>(null)
  const onChange = () => {
    bound(() => {
      const title = inputDom.current?.input?.value
      const filterMessage = title ? pdfAllList.filter(item => item.name.indexOf(title) !== -1) : pdfAllList
      setPdfList(transformResult(filterMessage))
    })
  }
  const [fileType, setFileType] = useState('')
  const uploadDom = useRef<{ showModal: Function }>(null)
  const addModal = () => {
    setFileType('')
    uploadDom.current?.showModal()
  }
  const addCate = (item: TResPdf) => {
    const addItem = (e: React.MouseEvent<HTMLElement, MouseEvent>, navitem: TResPdf) => {
      e.stopPropagation()
      setFileType(item.direction)
      uploadDom.current?.showModal()
    }
    return (
      <Button type="link" onClick={e => addItem(e, item)}>
        新增pdf
      </Button>
    )
  }
  return (
    <>
      <Bread bread={['pdf', 'pdf管理']}></Bread>
      <div className="pdf-header">
        <Input
          onChange={onChange}
          ref={inputDom}
          style={{ width: '200px', marginBottom: '16px' }}
          placeholder="根据用户名称搜索"
          suffix={<SearchOutlined style={{ color: 'rgba(0,0,0,.45)' }} />}
        />
        <div>
          <Button type={'primary'} onClick={addModal}>
            新增
          </Button>
        </div>
      </div>
      <UploadPdf ref={uploadDom} search={getPdfList} fileType={fileType}></UploadPdf>
      <Collapse defaultActiveKey={['0']}>
        {pdfList.map((groupitem, index) => (
          <Panel extra={addCate(groupitem)} header={groupitem.direction} key={index + ''}>
            <div className="pdf-item">
              {groupitem.pdfArr.map(item => (
                <Card
                  key={item.id}
                  title={item.name}
                  extra={
                    <>
                      <a href={item.pdf} style={{ marginLeft: '16px' }} target="_blank" rel="noreferrer">
                        预览
                      </a>{' '}
                      <a href="#" onClick={() => downloadPdf(item.id)}>
                        下载
                      </a>
                      {'  '}
                      <a href="#" style={{ color: 'red', marginLeft: '16px' }} onClick={() => showDeleteConfirm(item.id)}>
                        删除
                      </a>
                    </>
                  }
                  style={{ width: '31%', margin: '0 8px' }}
                >
                  <p>类型: {item.type}</p>
                  <p>文件大小: {item.size}</p>
                  <p>预览数:{item.seeNum}</p>
                  <p>下载数: {item.uploadNum}</p>
                </Card>
              ))}
            </div>
          </Panel>
        ))}
      </Collapse>
    </>
  )
}

export default Pdf
